package cn.lu.utils;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

public class FileUploadAndDownload {
    private String dirPath = "C:/server";

    public Result fileUpload(List<MultipartFile> multipartFileList, String serverPath, HttpServletRequest request) {
        //判断所上传文件是否存在
        if (!(!multipartFileList.isEmpty() && multipartFileList.size() > 0)) {
            return new Result(1, "文件为空", null);
        }
        for (MultipartFile file : multipartFileList) {
            //获取上传文件的原始名称
            String originalFilename = file.getOriginalFilename();
            //设置上传文件的保存地址目录
            String path = dirPath;
            if (serverPath != null) {
                path += serverPath + "/";
            } else {
                path += "/";
            }
            File filePath = new File(path);
            //如果保存的地址不存在,就先创建目录
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            //获取当前文件的后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //使用UUID重新命名上传的文件名称(UUID(唯一识别码)+原始文件名称后缀)
            String newFileName = UUID.randomUUID() + "." + suffix;
            try {
                file.transferTo(new File(path + newFileName));
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(1, "上传错误", null);
            }
            return new Result(0, "上传成功", serverPath+"/"+newFileName);
        }
        return new Result(1, "上传错误", null);
    }

    public ResponseEntity<byte[]> fileDownload(String filename, String serverPath, HttpServletRequest request) throws Exception {
        //指定要下载的文件所在的路径
        String path = dirPath;
        if (serverPath != null) {
            path += serverPath + "/";
        } else {
            path += "/";
        }
        //创建该文件对象
        File file = new File(path + filename);
        //对文件名编码,防止中午乱码
        //根据浏览器的不同进行编码设置,返回编码后的文件名
        //IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        //获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器,统一为UTF-8编码显示
                filename = URLEncoder.encode(filename, "UTF-8");
            }
        }
        //其他浏览器,火狐,谷歌,统一为ISO-8859-1编码显示
        filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //通知浏览器以下载的方式打开文件
        headers.setContentDispositionFormData("attachment", filename);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //使用spring MVC 框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }


}
